import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, AbstractControl } from '@angular/forms';

import { fuiTranslateService } from '../../i18n/i18n.module';
import { ValidatorBase } from './validator-base';

@Directive({
  selector: '[fuiMaxValue]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: MaxValueValidatorDirective,
      multi: true,
    },
  ],
})
export class MaxValueValidatorDirective extends ValidatorBase {
  private maxValue: number;

  constructor(private translate: fuiTranslateService) {
    super();
  }

  /** Max value for validation. */
  @Input() set fuiMaxValue(value: number) {
    this.maxValue = +value;
    this.triggerValidate();
  }

  validate(control: AbstractControl): {[validator: string]: string | boolean} {
    if (this.isNotValue(control.value) || this.isNotValue(this.maxValue)) {
      return null;
    }

    const value = +control.value;
    if (this.isNotNumber(value) || this.isNotNumber(this.maxValue)) {
      return null;
    }

    if (value <= this.maxValue) {
      return null;
    }

    return { fuiMaxValue: `${this.translate.translateKey('fui.FORM.INPUT_MAX_VALUE_ERROR')} ${this.maxValue}` };
  }

  private isNotValue(value) {
    return [undefined, null].indexOf(value) > -1;
  }

  private isNotNumber(value) {
    return isNaN(value) || !isFinite(value);
  }
}
